package com.jiayou


import android.annotation.SuppressLint
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSON
import com.qmuiteam.qmui.skin.handler.QMUISkinRuleColorStateListHandler
import com.qmuiteam.qmui.skin.handler.QMUISkinRuleMoreBgColorHandler
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.android.synthetic.main.activity_main.*
import org.java_websocket.WebSocket
import java.net.URI
import java.util.*
import kotlin.collections.ArrayList
import kotlin.concurrent.thread


/**
@author 李 双
@data   2020-09-11  11:29
@info   游戏主界面
 */
class GameActivity : AppCompatActivity(), View.OnClickListener {
    private val properties = Properties()

    var GAMEMODE: Int = 2                      //游戏模式(默认正常模式)
    lateinit var WS_URL: String                 //ws地址

    lateinit var client: Client                             //ws连接对象
    lateinit var tip: QMUITipDialog                     //匹配中Dialog
    var messageChannel: MessageChannel? = null         //对局数据

    var musicID = ArrayList<Int>()           //游戏音效ID
    lateinit var mMediaPlayer1: MediaPlayer  //van音效
    lateinit var mMediaPlayer2: MediaPlayer  //正常音效
    lateinit var victort: MediaPlayer  //游戏胜利
    lateinit var fail: MediaPlayer     //游戏失败

    lateinit var bgm1: MediaPlayer             //bgm  -> van BGM
    lateinit var bgm2: MediaPlayer             //bgm  -> 休闲 BGM

    var isOpenMusic = true    //音乐开关（默认开启）

    var go = ""               //现在该谁走棋
    var flag: Int = 0         //玩家标识

    @SuppressLint("HardwareIds")
    var user: String = ""         //用户名 -> SN号
    var name: String = ""         //昵称   -> 手机型号

    @SuppressLint("HardwareIds", "WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        properties.load(application.assets.open("ws.properties"))    //加载配置文件
        GAMEMODE = properties["game.model"].toString().toInt()                //获取游戏模式配置
        WS_URL = properties["ws.url"].toString()                              //获取ws地址配置
        isOpenMusic = properties["game.music"].toString().toBoolean()         //获取音效配置

        user = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) //获取机器的SN
        name = Build.BRAND + "-" + Build.MODEL                                        //获取机器的厂家+型号


        //由于ws的字符不能带空格字符，顾要去空格
        user = user.replace(" ", "")   //去空格
        name = name.replace(" ", "")   //去空格


        //加载音乐
        thread {
            for (i in 1..109)
                musicID.add(resources.getIdentifier("tip$i", "raw", "com.jiayou"))
            mMediaPlayer1 = MediaPlayer.create(this, musicID.random())
            mMediaPlayer2 = MediaPlayer.create(this, R.raw.tip110)
            victort = MediaPlayer.create(this, R.raw.vectory)
            fail = MediaPlayer.create(this, R.raw.fail)
            bgm1 = MediaPlayer.create(this, R.raw.bgm1)
            bgm2 = MediaPlayer.create(this, R.raw.bgm2)

            if (isOpenMusic)
                if (GAMEMODE == 1)
                    bgm1.start()
                else
                    bgm2.start()

            runOnUiThread { Toast.makeText(this, "音频加载完毕！", Toast.LENGTH_SHORT).show() }
        }


        //连接游戏服务器
        thread {
            try {
                client = Client(this, URI("$WS_URL/$user/$name"))
                client.connect()
                while (client.readyState != WebSocket.READYSTATE.OPEN) {
                    Thread.sleep(3000)
//                    runOnUiThread { Toast.makeText(this, "连接服务器中。。。", Toast.LENGTH_SHORT).show() }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }


        //开始匹配
        match.setOnClickListener {
            tip = QMUITipDialog.Builder(this)//创建tipdialog实例为其设置显示样式
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)//设置有加载框模式的dialog
                .setTipWord("匹配中...")
                .create();
            tip.show() //显示创建的tipDialog
            client.send(JSON.toJSON(MessageChannel(MessageState.READY, null)).toString())
        }
        match.setBackgroundColor(Color.parseColor("#00CC00"))
        match.setTextColor(Color.parseColor("#ffffff"))



        //重置游戏
        reset.setOnClickListener {
            try {
                client.close()
                client = Client(this, URI("$WS_URL/$user/$name"))
                client.connect()
                while (client.readyState.also { println(it) } != WebSocket.READYSTATE.OPEN) {
                    println("连接中···请稍后");
                    Thread.sleep(1000);
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            client.flag = 0
            messageChannel = null
            go = ""
            flag = 0
            l1.setBackgroundResource(R.drawable.line)
            l2.setBackgroundResource(R.drawable.line)
            l3.setBackgroundResource(R.drawable.line)
            l4.setBackgroundResource(R.drawable.line)
            l5.setBackgroundResource(R.drawable.line)
            l6.setBackgroundResource(R.drawable.line)
            l7.setBackgroundResource(R.drawable.line)
            l8.setBackgroundResource(R.drawable.line)
            l9.setBackgroundResource(R.drawable.line)
            match.isClickable = true
        }
        reset.setBackgroundColor(Color.parseColor("#0099FF"))
        reset.setTextColor(Color.parseColor("#ffffff"))


        //设置点击效果
        l1.setOnClickListener(this)
        l2.setOnClickListener(this)
        l3.setOnClickListener(this)
        l4.setOnClickListener(this)
        l5.setOnClickListener(this)
        l6.setOnClickListener(this)
        l7.setOnClickListener(this)
        l8.setOnClickListener(this)
        l9.setOnClickListener(this)

    }

    //重写程序结束方法
    override fun finish() {
        client.close()
        super.finish()
    }

    //播放音乐
    fun playMusic() {
        if (isOpenMusic) {
            if (GAMEMODE == 1) {
                if (mMediaPlayer1.isPlaying)
                    mMediaPlayer1.stop()
                mMediaPlayer1 = MediaPlayer.create(this, musicID.random())
                mMediaPlayer1.start()
            } else {
                if (mMediaPlayer2.isPlaying)
                    mMediaPlayer2.stop()
                mMediaPlayer2 = MediaPlayer.create(this, R.raw.tip110)
                mMediaPlayer2.start()
            }
        }
    }

    //检测谁赢了
    private fun checkWin(): String {

        val data = messageChannel?.data?.data
        var winner = ""


        //玩家一赢了
        if ((data?.get(0)?.get(0) == 1 && data[0][1] == 1 && data[0][2] == 1) ||
            (data?.get(1)?.get(0) == 1 && data[1][1] == 1 && data[1][2] == 1) ||
            (data?.get(2)?.get(0) == 1 && data[2][1] == 1 && data[2][2] == 1) ||

            (data?.get(0)?.get(0) == 1 && data[1][0] == 1 && data[2][0] == 1) ||
            (data?.get(0)?.get(1) == 1 && data[1][1] == 1 && data[2][1] == 1) ||
            (data?.get(0)?.get(2) == 1 && data[1][2] == 1 && data[2][2] == 1) ||

            (data?.get(0)?.get(0) == 1 && data[1][1] == 1 && data[2][2] == 1) ||
            (data?.get(2)?.get(0) == 1 && data[1][1] == 1 && data[0][2] == 1)
        ) {

            if (flag == 1) {
                showResoultDiglog()
                messageChannel?.data?.winner = messageChannel?.data?.player1.toString()
            } else {
                messageChannel?.data?.winner = messageChannel?.data?.player2.toString()
            }
            winner = messageChannel?.data?.winner.toString()
            return winner
        }


        //玩家二赢了
        if ((data?.get(0)?.get(0) == 2 && data[0][1] == 2 && data[0][2] == 2) ||
            (data?.get(1)?.get(0) == 2 && data[1][1] == 2 && data[1][2] == 2) ||
            (data?.get(2)?.get(0) == 2 && data[2][1] == 2 && data[2][2] == 2) ||

            (data?.get(0)?.get(0) == 2 && data[1][0] == 2 && data[2][0] == 2) ||
            (data?.get(0)?.get(1) == 2 && data[1][1] == 2 && data[2][1] == 2) ||
            (data?.get(0)?.get(2) == 2 && data[1][2] == 2 && data[2][2] == 2) ||

            (data?.get(0)?.get(0) == 2 && data[1][1] == 2 && data[2][2] == 2) ||
            (data?.get(2)?.get(0) == 2 && data[1][1] == 2 && data[0][2] == 2)
        ) {
            if (flag == 1) {
                messageChannel?.data?.winner = messageChannel?.data?.player1.toString()
            } else {
                showResoultDiglog()
                messageChannel?.data?.winner = messageChannel?.data?.player2.toString()
            }
            winner = messageChannel?.data?.winner.toString()
            return winner
        }

        return winner
    }

    //平局检测
    private fun checkDraw(): Boolean {
        var flag: Boolean = true
        val data = messageChannel?.data?.data
        data?.forEach { it ->
            it.forEach { its ->
                if (its == 0)
                    flag = false
            }
        }
        return flag
    }

    //点击事件监听
    override fun onClick(p0: View?) {
        playMusic()
        if (go == user)
            when (p0?.id) {
                R.id.l1 -> {
                    if (messageChannel?.data?.data?.get(0)?.get(0) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[0][0] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()
                        messageChannel?.data?.go = go


                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l1.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l1.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l2 -> {
                    if (messageChannel?.data?.data?.get(0)?.get(1) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[0][1] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l2.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l2.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l3 -> {
                    if (messageChannel?.data?.data?.get(0)?.get(2) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[0][2] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l3.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l3.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l4 -> {
                    if (messageChannel?.data?.data?.get(1)?.get(0) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[1][0] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()
                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l4.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l4.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l5 -> {
                    if (messageChannel?.data?.data?.get(1)?.get(1) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[1][1] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l5.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l5.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l6 -> {
                    if (messageChannel?.data?.data?.get(1)?.get(2) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[1][2] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }
                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l6.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l6.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }

                }
                R.id.l7 -> {
                    if (messageChannel?.data?.data?.get(2)?.get(0) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[2][0] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }
                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l7.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l7.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }

                }
                R.id.l8 -> {
                    if (messageChannel?.data?.data?.get(2)?.get(1) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[2][1] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }

                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l8.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l8.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }


                }
                R.id.l9 -> {
                    if (messageChannel?.data?.data?.get(2)?.get(2) == 0) {
                        val data = messageChannel?.data?.data
                        if (data != null) {
                            data[2][2] = flag
                        }
                        if (data != null) {
                            messageChannel?.data?.changeData(data)
                        }
                        //该谁走棋
                        go = if (go == messageChannel?.data?.player1)
                            messageChannel?.data?.player2.toString()
                        else
                            messageChannel?.data?.player1.toString()

                        messageChannel?.data?.go = go

                        //胜负
                        val winner = checkWin()
                        if (winner != "") {
                            messageChannel?.type =
                                MessageState.GAMEOVER
                            client.send(JSON.toJSON(messageChannel).toString())
                            go = ""
                            messageChannel = null
                            flag = 0
                        } else {
                            if (checkDraw()) {
                                showDrawDiglog()

                                messageChannel?.type =
                                    MessageState.DRAW
                                client.send(JSON.toJSON(messageChannel).toString())
                                go = ""
                                messageChannel = null
                                flag = 0
                            } else
                                client.send(JSON.toJSON(messageChannel).toString())
                        }

                        if (GAMEMODE == 1) {
                            l9.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player1 else R.drawable.player2)
                        } else
                            l9.setBackgroundResource(if (user == messageChannel?.data?.player1) R.drawable.player11 else R.drawable.player22)
                    }
                }
            }
    }


    //游戏胜负弹出框
    fun showResoultDiglog() {
        victort.start()
        if (GAMEMODE == 1) {
            QMUIDialog.MessageDialogBuilder(this)
                .setTitle("对局结束")
                .setMessage("恭喜你van♂了这局游戏!")
                .addAction(
                    "继♂续Van"
                ) { dialog, _ -> dialog.dismiss() }
                .show()
        } else {
            QMUIDialog.MessageDialogBuilder(this)
                .setTitle("对局结束")
                .setMessage("恭喜你赢得这局游戏！")
                .addAction(
                    "再来一把"
                ) { dialog, _ -> dialog.dismiss() }
                .show()
        }
    }


    //游戏平局弹出框
    fun showDrawDiglog() {
        QMUIDialog.MessageDialogBuilder(this)
            .setTitle("对局结束")
            .setMessage("平局平局!")
            .addAction(
                "再玩一把"
            ) { dialog, _ -> dialog.dismiss() }
            .show()
    }
}